package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.sensitiveword.requset.SensitiveWordCheckResult;
import com.blog.cmrpersonalblog.entity.Comment;
import com.blog.cmrpersonalblog.service.CommentManagementService;
import com.blog.cmrpersonalblog.service.SensitiveWordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 敏感词测试控制器
 * 用于测试敏感词管理系统与评论系统的集成效果
 */
@Slf4j
@RestController
@RequestMapping("/admin/sensitive-word-test")
@CrossOrigin(origins = "*", maxAge = 3600)
@SaCheckRole("admin")
public class SensitiveWordTestController {

   @Resource
    private SensitiveWordService sensitiveWordService;

   @Resource
    private CommentManagementService commentManagementService;

    /**
     * 测试敏感词检测
     */
    @PostMapping("/check")
    public Result<SensitiveWordCheckResult> testSensitiveWordCheck(@RequestParam String content) {
        log.info("测试敏感词检测，内容长度：{}", content != null ? content.length() : 0);
        try {
            SensitiveWordCheckResult result = sensitiveWordService.checkSensitiveWords(content);
            return Result.success("检测完成", result);
        } catch (Exception e) {
            log.error("敏感词检测失败", e);
            return Result.error("检测失败：" + e.getMessage());
        }
    }

    /**
     * 测试评论创建（包含敏感词处理）
     */
    @PostMapping("/test-comment")
    public Result<Map<String, Object>> testCommentCreation(@RequestParam String content,
                                                          @RequestParam(defaultValue = "1") Long articleId,
                                                          @RequestParam(defaultValue = "1") Long userId) {
        log.info("测试评论创建，内容：{}", content);

        Map<String, Object> result = new HashMap<>();

        try {
            // 先检测敏感词
            SensitiveWordCheckResult checkResult = sensitiveWordService.checkSensitiveWords(content);
            result.put("sensitiveWordCheck", checkResult);

            // 创建测试评论
            Comment comment = new Comment();
            comment.setContent(content);
            comment.setArticleId(articleId);
            comment.setUserId(userId);
            comment.setCreateTime(LocalDateTime.now());
            comment.setUpdateTime(LocalDateTime.now());

            try {
                boolean success = commentManagementService.createComment(comment);
                result.put("commentCreated", success);
                result.put("finalComment", comment);
                result.put("message", success ? "评论创建成功" : "评论创建失败");
            } catch (Exception e) {
                result.put("commentCreated", false);
                result.put("error", e.getMessage());
                result.put("message", "评论创建失败：" + e.getMessage());
            }

            return Result.success("测试完成", result);
        } catch (Exception e) {
            log.error("测试评论创建失败", e);
            return Result.error("测试失败：" + e.getMessage());
        }
    }

    /**
     * 刷新敏感词缓存
     */
    @PostMapping("/refresh-cache")
    public Result<String> refreshCache() {
        log.info("测试刷新敏感词缓存");
        try {
            sensitiveWordService.refreshSensitiveWords();
            return Result.success("缓存刷新成功", "敏感词缓存已刷新");
        } catch (Exception e) {
            log.error("刷新敏感词缓存失败", e);
            return Result.error("刷新失败：" + e.getMessage());
        }
    }

    /**
     * 获取敏感词统计信息
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        log.info("获取敏感词统计信息");
        try {
            Map<String, Object> stats = sensitiveWordService.getSensitiveWordStatistics();
            return Result.success("查询成功", stats);
        } catch (Exception e) {
            log.error("获取敏感词统计信息失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 验证敏感词配置
     */
    @GetMapping("/validate-config")
    public Result<Map<String, Object>> validateConfig() {
        log.info("验证敏感词配置");

        Map<String, Object> result = new HashMap<>();

        try {
            boolean isValid = sensitiveWordService.validateSensitiveWordConfig();
            result.put("isValid", isValid);
            result.put("message", isValid ? "敏感词配置正常" : "敏感词配置异常");

            // 获取统计信息
            Map<String, Object> stats = sensitiveWordService.getSensitiveWordStatistics();
            result.put("statistics", stats);

            return Result.success("验证完成", result);
        } catch (Exception e) {
            log.error("验证敏感词配置失败", e);
            return Result.error("验证失败：" + e.getMessage());
        }
    }

    /**
     * 测试敏感词管理控制器路由
     */
    @GetMapping("/check-routes")
    public Result<Map<String, Object>> checkRoutes() {
        log.info("检查敏感词管理路由");

        Map<String, Object> result = new HashMap<>();

        try {
            // 检查控制器是否可访问
            result.put("testControllerWorking", true);
            result.put("timestamp", System.currentTimeMillis());

            // 提供路由测试建议
            Map<String, String> routes = new HashMap<>();
            routes.put("分页查询", "GET /admin/sensitive-word/page");
            routes.put("获取详情", "GET /admin/sensitive-word/{id}");
            routes.put("创建敏感词", "POST /admin/sensitive-word");
            routes.put("更新敏感词", "PUT /admin/sensitive-word/{id}");
            routes.put("删除敏感词", "DELETE /admin/sensitive-word/{id}");
            routes.put("启用敏感词", "POST /admin/sensitive-word/{id}/enable");
            routes.put("禁用敏感词", "POST /admin/sensitive-word/{id}/disable");
            routes.put("更新状态", "PUT /admin/sensitive-word/{id}/status");
            routes.put("统计信息", "GET /admin/sensitive-word/statistics");

            result.put("availableRoutes", routes);
            result.put("note", "如果看到此消息，说明控制器扫描正常。请检查具体路由是否正确访问。");

            return Result.success("路由检查完成", result);
        } catch (Exception e) {
            log.error("检查路由失败", e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }
}